<?php

class AdminController extends FController
{
	
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'accessControl - Login Logout',
		);
	}
	
	public function accessRules( ){
		return array(
			array('allow', // allow authenticated users to access all actions
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		); 
	}
	/**
	 * @todo 退出登陆的操作
	 */
	public function actionLogout(){
		Yii::app()->user->logout();
		$this->redirect( $this->createUrl( 'admin/login' ) );
	}
	/**
	 * @todo 登陆首页顶部
	 */
	public function actionTop(){
//		$model=new User('search');
//        $model->unsetAttributes();  // clear any default values
//        if(isset($_GET['User']))
//            $model->attributes=$_GET['User'];
//
//        $this->render('admin',array(
//            'model'=>$model,
//        ));
//		
		$this->renderPartial('top' , array(
			'logoutUrl' => $this->createUrl( 'admin/logout' ),
			'user' => 'admin'
		) );
	}
	
	/**
	 * @todo 基本设置部份
	 */
	public function actionConfig(){
		$index_bottom="INDEX_BOTTOM";
		$array = array('QQ','SKYPE','MSN','SaleEmail','TEL','FAX','ZHAddress','ENAddress','Copyright');
		if ( isset( $_POST['submit'] ) ){
			//这是保存操作
			$submit_ary=array_merge(array($index_bottom),$array);
			foreach( $submit_ary as $value ){
				$val = $_POST[ $value ];
				$model = Config::model()->findByPk($value);
				$model->attributes = array(
					'ConfigKey' => $value ,
					'ConfigValue' => $val ,
				);
				$model->save();
			}
		}
		$datas = array();
		foreach( $array as $value ){
			$datas[ 'datas' ][$value] = Config::model()->findByPk($value)->ConfigValue;
		}
		$datas['index_bottom']=$index_bottom;
		$index_bottom_value=Config::model()->findByPk($index_bottom)->ConfigValue;
		$datas['index_bottom_value']=$index_bottom_value;
		$this->renderPartial('config' , $datas );
	}
	
	
	/**
	 * @todo 后台登陆判断
	 */
	public function actionLogin()	{
		if ( ! Yii::app()->user->isGuest ){
			$this->redirect( $this->createUrl( Yii::app()->params['adminHome'] ) );
		}
		$msg = '' ;
		if ( isset( $_POST['Submit'] ) ) {
			$model=new LoginForm;
			$model->attributes=$_POST;
			if($model->validate() && $model->login())
				$this->redirect( $this->createUrl( Yii::app()->params['adminHome'] ) ); 
			else
				$msg = '用户密或者密码不正确，登陆失败!';
		}
		$this->renderPartial('login' , array(
			'errorMsg' => $msg 
		));
	}

	/**
	 * @todo 后台登陆后首页
	 */
	public function actionIndex(){
//		var_dump( YiiBase::getPathOfAlias('webroot') );exit();
//		var_dump( Yii::app()->session->offSetGet() );exit();
		$this->renderPartial('index' , array(
			'leftUrl' => $this->createUrl( 'admin/left' ),
			'rightUrl' => $this->createUrl( 'admin/main' ),
			'topUrl' => $this->createUrl( 'admin/top' ),
		));
	}
	/**
	 * @todo 登陆后右边主界面
	 */
	public function actionMain(){
		$this->renderPartial('main');
	}
	/**
	 * @todo 后台登陆后首页左边部份
	 */
	public function actionLeft(){
		$language = strtoupper( Yii::app()->session->offSetGet( "FrontLanguage" ) );
		$language=empty($language)?'ZH':$language;
		$aboutusType=Yii::app()->params[$language.'aboutusType'];
		$typeAry=array_keys($aboutusType);
		$this->renderPartial('left' , array(
			'actionUrl' => array(
				'网站常规设置' => array(
					'基本设置' => $this->createUrl( 'admin/config' ),
					'修改密码'=>$this->createUrl('admin/cpass'),
					'关于我们'.$typeAry['0'] => $this->createUrl( 'admin/aboutus#'.$typeAry['0'] ),
					'关于我们'.$typeAry['1'] => $this->createUrl( 'admin/aboutus#'.$typeAry['1'] ),
					'关于我们'.$typeAry['2'] => $this->createUrl( 'admin/aboutus#'.$typeAry['2'] ),
					'问与答' => $this->createUrl( 'admin/faq' ),
					'联系我们' => $this->createUrl( 'admin/contactus' ),
					'首页轮循图片' => $this->createUrl( 'admin/repeatpic' ),
					'首页图片新增' => $this->createUrl( 'admin/createpic' ),
				),
				'产品设置' => array(
					'分类列表' => $this->createUrl( 'category/index' ),
					'分类新加' => $this->createUrl( 'category/create' ),
					'产品列表' => $this->createUrl( 'products/index' ),
					'产品新加' => $this->createUrl( 'products/create' ),
				),
			)
		) );
	}
	/**
	 * @todo 关于我们的设置
	 */
	function actionAboutus(){
		$language = strtoupper( Yii::app()->session->offSetGet( "FrontLanguage" ) );
		$language=empty($language)?'ZH':$language;
		$aboutusType=Yii::app()->params[$language.'aboutusType'];
		$typeAry=array_keys($aboutusType);
		foreach ($aboutusType as $tKey=>$tVal){
			$array[]='ENABOUTUS'.strtoupper($tKey);
			$array[]='ZHABOUTUS'.strtoupper($tKey);				
		}		
		if ( isset( $_POST['submit'] ) ){
			//这是保存操作

			//$array = array('ENABOUTUS','ZHABOUTUS','ENABOUTUSSUMMARY','ZHABOUTUSSUMMARY');
			foreach( $array as $value ){
				$val = $_POST[ $value ];
				$model = Config::model()->findByPk($value);
				$model->attributes = array(
					'ConfigKey' => $value ,
					'ConfigValue' => $val ,
				);
				$model->save();
			}
		}
		
		foreach ($array as $aval){		
			$datas[$aval] = Config::model()->findByPk($aval)->ConfigValue;
		}		
		//var_dump($datas);
		$href=$this->createUrl("admin/aboutus");
		$this->renderPartial('aboutus' , array(
			'href'=>$href,
			'typeAry'=>$typeAry,
			'datas'=>$datas,
		) );
	}
	
	/**
	 * 
	 * 修改密码
	 */
	function actionCpass()
	{
		
		$model=User::model()->findByPk(1);

		$error=false;
		$error_msg="";
		if( isset($_POST['submit']))
		{
			if(empty($_POST['oldPass']))
			{
				$error=true;
				$error_msg="旧密码不能为空！";					
			}
			if((empty($_POST['newPass']) || empty($_POST['rnewPass'])) && !$error)
			{
				$error=true;
				$error_msg="新密码不能为空！";				
			}
			if(($_POST['newPass']!=$_POST['rnewPass']) && !$error)
			{
				$error=true;
				$error_msg="密码和重复密码不相同！";
			}
			
		 	if((md5($_POST['oldPass'])!=$model->PassWord)  && !$error)
		 	{
		 		$error=true;
		 		$error_msg="旧密码不对！";
		 	}
		 	
		 	if(!$error && empty($error_msg)){
				$model->attributes = array(
					'PassWord' => md5($_POST['newPass']),
				);
				$model->save();	
		 		$error=true;
		 		$error_msg="修改成功！";				
		 	} 	
		 	
		 	
		 	
		}
		 
		//var_dump($error,$error_msg);
		$this->renderPartial('cpass' , array(
			'data'=>$model,
			'error'=>$error,
			'error_msg'=>$error_msg,
		 ));		 
	}
	
	/**
	 * @todo 联系我们的设置
	 */
	function actionContactus(){
		if ( isset( $_POST['submit'] ) ){
			//这是保存操作
			$array = array('ENCONTACTUS','ZHCONTACTUS');
			foreach( $array as $value ){
				$val = $_POST[ $value ];
				$model = Config::model()->findByPk($value);
				$model->attributes = array(
					'ConfigKey' => $value ,
					'ConfigValue' => $val ,
				);
				$model->save();
			}
		}
		$this->renderPartial('contactus' , array(
			'ENCONTACTUS' => Config::model()->findByPk('ENCONTACTUS')->ConfigValue ,
			'ZHCONTACTUS' => Config::model()->findByPk('ZHCONTACTUS')->ConfigValue ,
		) );
	}
	
	/**
	 * @todo faq
	 */
	function actionFaq(){
		if ( isset( $_POST['submit'] ) ){
			//这是保存操作
			$array = array('ENFAQ','ZHFAQ');
			foreach( $array as $value ){
				$val = $_POST[ $value ];
				$model = Config::model()->findByPk($value);
				$model->attributes = array(
					'ConfigKey' => $value ,
					'ConfigValue' => $val ,
				);
				$model->save();
			}
		}
		$this->renderPartial('faq' , array(
			'ENFAQ' => Config::model()->findByPk('ENFAQ')->ConfigValue ,
			'ZHFAQ' => Config::model()->findByPk('ZHFAQ')->ConfigValue ,
		) );
	}	
	
	public function ActionRepeatpic()
	{
		//取得每页显示多少个
		$pageNum = Yii::app()->params['adminGirdPageNum'];
		$totalNum = Indexpic::model()->count();
		$pages=new CPagination($totalNum);
		$pages->pageSize=$pageNum;
		$criteria=new CDbCriteria();
		$pages->applyLimit($criteria);
		$datas = Indexpic::model()->findAll( 'ID>:ID ORDER BY :order limit :offset,:limit ' , array(
			':ID' => 0 ,
			':order' =>'Sorts' ,
			':offset' => $pages->currentPage*$pages->pageSize ,
			':limit' => $pages->pageSize
		) );
		$this->renderPartial('repeatpiclist' , array(
			'datas'=>$datas,
			'totalNum'=>$totalNum,
			'pages'=>$pages,
		));
	}
	
	public function ActionUpdatepic($ID)
	{
		$model=new Indexpic;
		
		$ID=intval($ID);
		$model=new Indexpic;
		
			
		if(!empty($ID))
		{
			$model=Indexpic::model()->findByPk($ID);
			if(!$model->ID)
			{
				throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
			}
		}else{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}		

		
		$upload_dir=Yii::app()->params['uploadFile'];
		$base_upload_dir=Yii::app()->basePath.DS.$upload_dir;
				
		if(isset($_POST['Indexpic']))
		{
			$model->attributes=$_POST['Indexpic'];
			$file=CUploadedFile::getInstance($model,'PicPath');
			if($file){		
				$newname=date('YmdHmss',time()).'.'.$file->extensionName;
				$picpath=$upload_dir.'index'.DS.$newname;
				$picpath=str_replace(DS, '/',$picpath);
				$model->PicPath = $picpath;				
				$file->saveAs($model->PicPath);//上传到服务器	
			}		
			if($model->save())
				$this->redirect(array('repeatpic'));
		}		
		$this->renderPartial('repeatpic' , array('model'=>$model) );		
	}
	
	
	public function ActionCreatePic()
	{
		$model=new Indexpic;
		$upload_dir=Yii::app()->params['uploadFile'];
		$base_upload_dir=Yii::app()->basePath.DS.$upload_dir;
				
		if(isset($_POST['Indexpic']))
		{
			$model->attributes=$_POST['Indexpic'];
			$file=CUploadedFile::getInstance($model,'PicPath');
			if($file){		
				$newname=date('YmdHmss',time()).'.'.$file->extensionName;
				$picpath=$upload_dir.'index'.DS.$newname;
				$picpath=str_replace(DS, '/',$picpath);
				$model->PicPath = $picpath;				
				$file->saveAs($model->PicPath);//上传到服务器	
			}		
			if($model->save())
				$this->redirect(array('repeatpic'));
		}		
		$this->renderPartial('repeatpic' , array('model'=>$model) );
	}
	
	public function ActionDelPic($ID)
	{
		$ID=intval($ID);
		if(!empty($ID))
		{
			// we only allow deletion via POST request
			$model=new Indexpic;
			$imgdir=Indexpic::model()->findByPk($ID)->PicPath;
			if($imgdir && file_exists($imgdir))
			{
				unlink($imgdir);
			}
			if(Indexpic::model()->deleteByPk($ID))
			{
				$this->redirect(array('repeatpic'));
			}
		}
		else{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}		
	}
}